import axios from 'axios'
import { Message, MessageBox, Notification } from 'element-ui'
import store from '@/store'
import { getToken, TokenKey } from '@/utils/auth'
import { tansParams,removeNull } from '@/utils/wanyun'

// create an axios instance
const service = axios.create({
  baseURL: process.env.BASE_API, // api 的 base_url
  timeout: 60000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // Do something before request is sent
    // console.log('config',config)
    if (store.getters.token) {
      config.headers[TokenKey] = getToken()
    }
    if(config.admin !== false) {
      config.baseURL = config.baseURL + 'admin'
    }

    if(config.headers['Content-Type']) config.headers['Content-Type'] = config.headers['Content-Type']
    // get请求映射params参数
    if (config.method === 'get' && config.params) {
      let url = config.url + '?' + tansParams(config.params)
      url = url.slice(0, -1)
      config.params = {}
      config.url = url
    }
    if(config.data) {
      let data = config.data || {}
      data = removeNull(data)
      config.data = data
    }
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)
export const isRelogin = { show: false }
// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.resultCode === 0 || res.resultCode === '0' || res.type === 'application/octet-stream' || response.headers['content-type'] === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8') {
      return res
    } else if (res.resultCode == 300000) { // 未登录
      if (!isRelogin.show) {
        isRelogin.show = true
        MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', { confirmButtonText: '重新登录', cancelButtonText: '取消', type: 'warning' }).then(() => {
          isRelogin.show = false
          store.dispatch('FedLogOut').then(() => {
            location.reload()
          })
        }).catch(() => {
          isRelogin.show = false
        })
      }
      return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
    } else if (res.resultCode == 300001) { // 没有权限
      Notification.error({ title: '没有操作权限，请联系管理员授权' })
      return Promise.reject()
    } else {
      Message({
        message: res.resultMsg,
        type: 'error',
        duration: 5 * 1000
      })
      // 非5xx的错误属于业务错误，留给具体页面处理
      return Promise.reject(response)
    }
  }, error => {
    Message({
      message: '服务器繁忙，请联系管理员',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  })

export function download(url, params, filename) {
  return service.post(url, params, {
    headers: { 'Content-Type': 'application/json' },
    responseType: 'blob'
  }).then(async(data) => {
    const url = window.URL.createObjectURL(data.data) // 创建一个临时的url指向blob对象
    const a = document.createElement('a')
    a.href = url
    a.download = `${filename}.xlsx`
    a.click()
  }).catch((r) => {
    console.error(r)
    Message.error('下载文件出现错误，请联系管理员！')
  })
}

export default service
